package com.siyoumi.app.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.app.entity.SysStock;
import com.siyoumi.app.mapper.SysStockMapper;
import com.siyoumi.component.XApp;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.exception.XException;
import com.siyoumi.service.ServiceImplBase;
import com.siyoumi.util.XReturn;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.validator.XValidator;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


//t_s_stock
@Service
public class SysStockService
        extends ServiceImplBase<SysStockMapper, SysStock> {
    static public SysStockService getBean() {
        return XSpringContext.getBean(SysStockService.class);
    }


    public SysStock getEntityBySrc(String idSrc) {
        return getEntityBySrc(idSrc, false);
    }

    /**
     * 库存
     *
     * @param idSrc 来源ID
     * @param lock  true：锁
     */
    public SysStock getEntityBySrc(String idSrc, Boolean lock) {
        QueryWrapper<SysStock> query = q().eq("stock_id_src", idSrc);
        return first(query, lock);
    }

    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public SysStock updateLeft(String idSrc, Long newLeft, Long oldLeft) {
        SysStock entityStock = getEntityBySrc(idSrc, true);
        if (!entityStock.getStock_count_left().equals(oldLeft)) {
            throw new XException(XReturn.getR(20038, idSrc + ":余量异常，请刷新页面"));
        }

        SysStock entityUpdate = new SysStock();
        entityUpdate.setStock_id(Long.valueOf(entityStock.getKey()));
        entityUpdate.setStock_count_left(newLeft);
        saveOrUpdatePassEqualField(entityStock, entityUpdate);

        entityStock.setStock_count_left(newLeft);

        return entityStock;
    }


    /**
     * 减库存
     *
     * @param idSrc
     * @param useNum 传2：减2库存，传-1：加1库存
     */
    @SneakyThrows
    public Boolean subStock(String idSrc, Long useNum) {
        if (!XApp.isTransaction()) {
            XValidator.err(EnumSys.SYS.getErrcode(), "请开事务");
        }

        SysStock entityStock = getEntityBySrc(idSrc, true);
        if (useNum > 0) {
            if (entityStock.getStock_count_left() < useNum) {
                XValidator.err(EnumSys.SYS.getErrcode(), idSrc + ":库存扣减失败");
            }
        }

        SysStock entityUpdate = new SysStock();
        entityUpdate.setStock_id(Long.valueOf(entityStock.getKey()));
        entityUpdate.setStock_count_use_add(useNum.intValue());
        updateById(entityUpdate);

        return true;
    }
}
